package com.karina.visualization.chart.component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.karina.visualization.chart.model.CategorizedSeriesModel;
import com.karina.visualization.chart.model.ChartModel.DataDescriptor;
import com.karina.visualization.chart.model.SeriesModel;
import com.karina.visualization.chart.model.SeriesModel.CategoryValue;

public class DefaultCategoryDataDescriptor implements
		DataDescriptor<Map<String, Object>> {

	private final String xproperty;

	public DefaultCategoryDataDescriptor(String xproperty) {
		this.xproperty = xproperty;
	}

	@Override
	public String getDescription(Map<String, Object> item) {
		return getLabel(item);
	}

	@Override
	public String getLabel(Map<String, Object> item) {
		return item.get(xproperty).toString();
	}

	@Override
	public List<SeriesModel> createSeries(List<Map<String, Object>> items) {

		List<SeriesModel> serieses = new ArrayList<SeriesModel>();
		for (Map<String, Object> value : items) {
			for (Entry<String, Object> entry : value.entrySet()) {
				if (entry.getKey().equals(xproperty))
					continue;

				SeriesModel se = searchSeriesModel(serieses, entry);
				if (se == null) {
					se = new CategorizedSeriesModel();
					se.setName(entry.getKey());
					serieses.add(se);
				}
				List values = (List) se.getValue();
				if (values == null) {
					values = new ArrayList<SeriesModel.CategoryValue>();
				}
				CategoryValue cvalue = new CategoryValue();
				cvalue.setValue(entry.getValue().toString());
				cvalue.setCategory(getLabel(value));
				cvalue.setDescription(getDescription(value));
				values.add(cvalue);
				se.setValue(values);
			}
		}

		return serieses;
	}

	private SeriesModel searchSeriesModel(List<SeriesModel> serieses,
			Entry<String, Object> entry) {
		for (SeriesModel s : serieses) {
			if (s.getName().equals(entry.getKey())) {
				return s;
			}
		}
		return null;
	}

}
